package com.azzcs.springbootkafka.service;

import org.apache.kafka.clients.producer.RecordMetadata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.concurrent.ExecutionException;

/**
 * @Author: wzg
 * @Date: 2021/4/22 下午3:54
 */
@Service
public class KafkaService {
    @Autowired
    private KafkaTemplate<Integer,String> kafkaTemplate;


    @Transactional(rollbackFor = Exception.class)
    public void sendMessage(String message) {
        kafkaTemplate.send("spring-boot-topic",message);
        int i = 1/0;
        kafkaTemplate.send("spring-boot-topic",message);
    }

    @Transactional(rollbackFor = Exception.class)
    public void sendSyncMessage(String message) throws ExecutionException, InterruptedException {
        ListenableFuture<SendResult<Integer, String>> feature = kafkaTemplate.send("spring-boot-topic", message);
        SendResult<Integer, String> result = feature.get();
        RecordMetadata metadata = result.getRecordMetadata();
        System.out.println(metadata.topic());
        System.out.println(metadata.partition());
        System.out.println(metadata.offset());
        System.out.println(metadata.toString());
    }
}
